# -*- encoding: utf-8 -*-

"""
@File:      tc_libtdb_libtdb_func_003.py.py
@Time:      2024/04/17 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libtdb_libtdb_func_003.py.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libtdb libtdb-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >ltdb_test3.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tdb.h>
#include <fcntl.h>

// 遍历数据库记录时的回调函数
static int traverse_callback(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA data, void *private_data) {
    (void)tdb;        // 未使用的参数
    (void)private_data; // 未使用的参数
    printf("键: %.*s, 值: %.*s\\n", key.dsize, key.dptr, data.dsize, data.dptr);
    return 0; // 返回0继续遍历，返回-1中断遍历
}

int main() {
    TDB_CONTEXT *tdb;
    TDB_DATA key, data;
    int ret;

    // 创建或打开数据库
    tdb = tdb_open("ltdb_test3.tdb", 0, TDB_DEFAULT, O_CREAT | O_RDWR, 0644);
    if (tdb == NULL) {
        fprintf(stderr, "无法打开或创建数据库\\n");
        return EXIT_FAILURE;
    }

    // 添加一些键值对作为测试数据，确保键和值为字符串
    char *keys[] = {"key1", "key2", "key3"};
    char *values[] = {"value1", "value2", "value3"};
    
    for (int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
        key.dptr = (unsigned char *)keys[i];
        key.dsize = strlen(keys[i]) + 1;
        data.dptr = (unsigned char *)values[i];
        data.dsize = strlen(values[i]) + 1;
        ret = tdb_store(tdb, key, data, TDB_REPLACE);
        if (ret != 0) {
            fprintf(stderr, "添加键值对%s失败\\n", keys[i]);
            tdb_close(tdb);
            return EXIT_FAILURE;
        }
    }

    // 遍历数据库中的所有记录
    printf("数据库内容:\\n");
    ret = tdb_traverse(tdb, traverse_callback, NULL);
    if (ret == -1) {
        fprintf(stderr, "遍历数据库时出错\\n");
    } else {
        printf("遍历了 %d 条记录\\n", ret);
    }

    // 关闭数据库
    tdb_close(tdb);

    printf("所有操作执行完毕\\n");

    return EXIT_SUCCESS;
}
EOF'''
        self.cmd(cmdline)


    def test(self):
        self.cmd("gcc -o ltdb_test3 ltdb_test3.c -ltdb")
        code, ltdb_result = self.cmd("./ltdb_test3")
        self.assertIn('所有操作执行完毕', ltdb_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf ltdb_test3.c ltdb_test3 ltdb_test3.tdb")
